﻿$(document).ready(function () {
    SP.SOD.executeFunc('sp.runtime.js', 'SP.ClientContext', function () { /*alert("sp.runtime.js loaded");*/ });
    SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function () { /*alert("sp.js loaded");*/ });
    ExecuteOrDelayUntilScriptLoaded(GlobalNavInit, "SP.js");
});

function GlobalNavInit() {
    var taxonomySodLoaded = false;

    if (typeof (_v_dictSod) !== 'undefined' && _v_dictSod['SP.Taxonomy.js'] == null) {
        SP.SOD.registerSod('SP.Taxonomy.js', SP.Utilities.Utility.getLayoutsPageUrl('SP.Taxonomy.js'));
    }
    else {
        taxonomySodLoaded = _v_dictSod['SP.Taxonomy.js'].state === Sods.loaded;
    }

    if (taxonomySodLoaded) {
        Function.createDelegate(this, GlobalNavLoad)();
    }
    else {
        SP.SOD.executeFunc('SP.Taxonomy.js', false, Function.createDelegate(this, GlobalNavLoad));
    }
}

function GlobalNavLoad() {
    //Current Context
    var context = SP.ClientContext.get_current();

    //Current Taxonomy Session
    var taxSession = SP.Taxonomy.TaxonomySession.getTaxonomySession(context);

    //Term Stores
    var termStores = taxSession.get_termStores();

    //Name of the Term Store from which to get the Terms.
    var termStore = termStores.getByName("Managed Metadata Service");

    //GUID of Term Set from which to get the Terms.

    //Production
    //var termSet = termStore.getTermSet("16d0c284-d6cc-4ed6-8473-56beb890762a");

    //Test
    //var termSet = termStore.getTermSet("0583b586-0524-4adb-b9f4-aaa23ff55ead");

    //Dev
    var termSet = termStore.getTermSet("fd8c805b-d23b-446c-88e8-8150244eb5ed");

    var terms = termSet.getAllTerms();

    context.load(terms);

    context.executeQueryAsync(function () {
        var termEnumerator = terms.getEnumerator();
        var termName;
        var termUrl;
        var globalNav = "";
        while (termEnumerator.moveNext()) {
            var currentTerm = termEnumerator.get_current();
            termName = currentTerm.get_name();
            termUrl = currentTerm.get_localCustomProperties()['_Sys_Nav_SimpleLinkUrl'];
            globalNav += "<a href='" + termUrl + "'>" + termName + "</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
        }

        $get("globalNav").innerHTML = globalNav;

    }, function (sender, args) {
        console.log(args.get_message());
    });
}